package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 VoucherOrderServiceImpl里使用的是普通锁，而
 此类VoucherOrderServiceImpl2使用的是用redis实现的分布式锁，
 为了保存代码里的思考笔记，所以保存了两份
 */
@Service
public class VoucherOrderServiceImpl2 extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    private static final String SEC_KILL = "SEC_KILL";
    @Autowired
    SeckillVoucherMapper seckillVoucherMapper;

    @Autowired
    VoucherOrderMapper voucherOrderMapper;



    @Autowired
    ISeckillVoucherService seckillVoucherService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisIdWorker redisIdWorker;

    @Override
    public  Result seckill(Long voucherId) {
        //1.查询优惠券信息，看是否在销售时间段
        SeckillVoucher seckillVoucher = seckillVoucherMapper.selectById(voucherId);
        LocalDateTime nowTime = LocalDateTime.now();
        if (nowTime.isBefore(seckillVoucher.getBeginTime()) || nowTime.isAfter(seckillVoucher.getEndTime())){
            return Result.fail("优惠券不在销售时间内");
        }
        Long userId = UserHolder.getUser().getId();
        VoucherOrderServiceImpl2 proxy = (VoucherOrderServiceImpl2)AopContext.currentProxy();
        //注意这里需要锁的是同一个用户，不同用户是可以并行的
        SimpleRedisLock redisLock = new SimpleRedisLock("order:" + userId , stringRedisTemplate);
        if (!redisLock.tryLock(1200)) {
            return Result.fail("一个用户只能下一单");
        }
        try {
            return proxy.createOrder(voucherId, seckillVoucher);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //锁的释放注意要放到finally
            redisLock.unlock();
        }
        return Result.fail("服务端出现异常");
    }


    @Transactional
    public Result createOrder(Long voucherId, SeckillVoucher seckillVoucher) {
        //一人一单，先查询数据库中该用户是否已经下单
        QueryWrapper<VoucherOrder> condition = new QueryWrapper<VoucherOrder>().eq("voucher_id", voucherId).eq("user_id", UserHolder.getUser().getId());
        int count = count(condition);
        if (count > 0) {
            return Result.fail("一人只能下一单");
        }


        if (seckillVoucher.getStock() <= 0) {
            return Result.fail("优惠券已售完");
        }

        //2.扣减订单库存
        boolean success = seckillVoucherService.update().setSql("stock = stock - 1").gt("stock", 0).update();
        if (!success) {
            return Result.fail("优惠券已售完");
        }

        //3.生成订单
        VoucherOrder voucherOrder = new VoucherOrder();
        Long orderId = redisIdWorker.nextId(SEC_KILL);
//        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrderMapper.insert(voucherOrder);
        return Result.ok("订单id:" + orderId);
    }
}
